import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ActionSheetController, AlertController } from "@ionic/angular";
import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { PageModalService } from '../../shared/service/page-modal-service';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { IndexedDBService } from '../../shared/service/indexed-db.service';
import { TabsService } from './../../shared/service/tabs.service';
import { ChatService } from 'src/app/shared/service/chatService';
declare let $: any;

@Component({
  selector: 'app-chatonline',
  templateUrl: './chatonline.component.html',
  styleUrls: ['./chatonline.component.scss'],
})
// tslint:disable
export class ChatonlineComponent implements OnInit {

  @ViewChild('chatonline_container') content;
  constructor(
    // private navParams: NavParams,
    // private modalController: ModalController,
    public route: ActivatedRoute,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    public eventService: EventService,
    public chatService: ChatService,
    private http: HttpService,
    private indexedDBService: IndexedDBService,
    public appGlobalService: AppGlobalService,
    public pageModalService: PageModalService,
    private tabsService: TabsService,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    this.eventService.eventEmit.on("sendSelectItemMsg", (obj) => {
      const reqTag = localStorage.getItem('sendSelectItemMsg');
      if (reqTag) {
        localStorage.removeItem('sendSelectItemMsg');
        this.sendSelectItemMsg(obj);
      }
    });

    this.eventService.eventEmit.on("refreshChatMsg", (obj) => {
      // this.refreshListData(obj);
      this.messages = [];
      this.jid = String(this.itemObj.id).split('-')[1];
      this.toId = String(this.itemObj.id).split('-')[0];
      this.toId = this.chatService.currentTalkNo;
      this.itemObj.id = this.toId + '-' + this.jid;
      this.indexedDBService.getAllValues('chat', (obj) => {
        obj.onsuccess = (event) => {
          const cursor = event.target.result;
          if (cursor) {
            if (String(cursor.key).indexOf(this.chatService.currentTalkNo) !== -1) {
              const parseObj = cursor.value;
              parseObj.key = cursor.key;
              this.messages.push(parseObj);
              this.changeDetectorRef.markForCheck();
              this.changeDetectorRef.detectChanges()
            }
            cursor.continue();
          } else {
            if (this.messages.length === 0) {
              // this.webSocketService.sendCommandEnterGroupsForChatOnline(String(this.itemObj.id).split('-')[0]);
              console.log('chatonline.component', 'data empty!');
            }
            this.content.scrollToBottom(0);
          }
        };
      });
    });
  }
  text: Text;
  messages = [];
  nickname = '';
  message_text = '';
  more = false;
  itemObj: any;
  shareShow = null;
  input: any;
  ifLogin;
  jid = "";
  toId = "";
  fromAvatarUrl = 'assets/img/head.png';
  toAvatarUrl = 'assets/img/head.png';
  searchListData;
  caseListData;
  isPxw = this.appGlobalService.clientType;
  chatModalId = new Date().getTime() + '-chat';
  showType = 'normal';
  isHiddenAddBtn = '0';
  addBtnId = 'addBtnId' + new Date().getTime();
  moreBtnId = 'moreBtnId' + new Date().getTime();
  textareaId = 'textareaId' + new Date().getTime();
  sendBtnId = 'sendBtnId' + new Date().getTime(); // 2024.08.05 防止发送按钮展示异常一会显示一会不显示
  limitEnterChat = true;
  showMoreInfoBox = false;
  autoTriger = false;

  ngOnInit() {
    this.autoTriger = true;
    const that = this;
    this.messages = [];
    this.chatService.pageNo = 0;
    this.ifLogin = localStorage.getItem('userId') !== 'null';

    this.appGlobalService.consoleLog('进入聊天详情页面0', '...');

    // 2023.12.01 路由
    this.route.queryParams.subscribe(p => {

      this.appGlobalService.consoleLog('进入聊天详情页面1', '...');
      // 2023.12.01 防止路由重复进入多次
      if (p === null || p === undefined) {
        console.log('enter chatOnline router', p);
        return;
      }
      this.itemObj = JSON.parse(p.item);
      if (!this.toId) {
        this.toId = this.itemObj.toId;
      }
      this.jid = localStorage.getItem('userId');
      if (this.itemObj) {
        if (p.hiddenAddBtn !== undefined) {
          if (p.hiddenAddBtn === "true") {
            setTimeout(() => {
              $('#' + this.addBtnId).hide();
            }, 50);
          } else {
            setTimeout(() => {
              $('#' + this.addBtnId).show();
            }, 50);
          }
        }
        //1.6.34 新增参数用于联系卖家发送订单信息
        if (this.itemObj['linkParams'] !== undefined) {
          setTimeout(() => {
            const nowDate = Date.now();
            const msgKey = this.jid + '-' + this.toId + '-' + nowDate;
            console.log('msgKey=', msgKey);
            if (this.itemObj['linkParams'].chatType === 'order') {
              localStorage.setItem('onSendWebSocketMessageTag', 'true');
              // 发送订单信息
              this.eventService.eventEmit.emit("onSendWebSocketMessage",
                {
                  disableClick: true, // 不可点击
                  text: this.itemObj['linkParams'].orderTitle,
                  toId: this.toId,
                  fromId: this.jid,
                  key: this.itemObj.id,
                  type: 'opp',
                  opportunity_id: '',
                  title: this.itemObj['linkParams'].orderTitle,
                  rentunit: '元/月',
                  imags: this.itemObj['linkParams'].orderImage,
                  pluginId: '1',
                  big_district: this.itemObj['linkParams'].orderNo,
                  district: 'district',
                  area: 'area',
                  industry: 'industry',
                  rent: 'rent',
                  transfer_fee: 'transfer_fee',
                  nowDate
                });
              this.messages.push({
                msg:
                {
                  disableClick: true,
                  text: this.itemObj['linkParams'].orderTitle,
                  type: 'opp',
                  opportunity_id: '',
                  title: this.itemObj['linkParams'].orderTitle,
                  imags: this.itemObj['linkParams'].orderImage,
                  pluginId: '1',
                  rentunit: '元/月',
                  from: this.jid,
                  big_district: this.itemObj['linkParams'].orderNo,
                  district: 'district',
                  area: 'area',
                  industry: 'industry',
                  rent: 'rent',
                  transfer_fee: 'transfer_fee'
                }, datetime: this.appGlobalService.getNowFormatDateYYYYMMDDHHMM(),
                key: msgKey
              });
            }
          }, 2500);
        }
        if (this.itemObj.nickname) {
          this.nickname = this.itemObj.nickname;
        }
        localStorage.setItem('isEnterDetailChatPage', this.itemObj.id);
        if (this.itemObj.id) {
          if (this.ifLogin) {
            that.chatService.getChatHistoriesByFriendNo(this.itemObj.toId, (messageList) => {
              this.appGlobalService.consoleLog('消息读取成功！', messageList);
              this.http.hideLoading();
            });
          } else {
            this.appGlobalService.consoleLog('账号未登录！', '  	   ');
          }

        }
      }
    });
  }


  getJidAvatarUrl(callbakFunction: Function) {

    this.indexedDBService.getByKey(this.jid, 'user', (userData) => {
      userData.onsuccess = (userEvent) => {
        if (userData.result) {
          const userObj = userData.result;
          callbakFunction(userObj);
        } else {
          // callbakFunction({ avatar_url:
          // 'assets/icon/IM_customer service@3x.png', identity: '北京员工', nickname: '深圳qac', work_mobile: null });
          this.http.get("message/userinfo/im/" + this.jid, (response) => {
            const data = response.data;
            if (this.jid.includes('random')) {
              data.nickname = '访客';
            }
            this.indexedDBService.add(data, this.jid, 'user');
            callbakFunction(data);
          }, (error) => {
            console.log('msg-----> error:' + JSON.stringify(error));
          });
        }
      };
    });
  }


  // 2023.12.01 统一处理返回
  async goBack() {
    try {
      localStorage.removeItem('isEnterDetailChatPage');
      this.appGlobalService.goBack();
      // if (this.itemObj['currentPath'] && this.itemObj['currentPath'].includes('nav1')) {
      //   this.appGlobalService.goBack();
      // } else {
      //   if (localStorage.getItem('chatPageFrom')) {
      //     localStorage.removeItem('chatPageFrom');
      //     this.eventService.eventEmit.emit(this.tabsService.tabPage, '1');
      //     await setTimeout(() => {
      //       localStorage.setItem('refreshFixedTabInvationMsgTag', '1');
      //       this.eventService.eventEmit.emit('refreshFixedTabInvationMsg', '1');
      //       localStorage.setItem('refreshUnreadChatListMsgTag', '1');
      //       this.eventService.eventEmit.emit('refreshUnreadChatListMsg', '1');
      //     }, 100);
      //     await setTimeout(() => {
      //       this.appGlobalService.goBack();
      //     }, 500);
      //   } else {
      //     this.appGlobalService.goBack();
      //   }
      // }
    } catch (error) {
    }
  }

  sendMessage() {
    try {
      if (this.message_text.trim().length === 0) {
        return;
      }
      let tel = '';
      // 新增临时需求
      if (this.message_text.includes('tel:')) {
        const startPos = this.message_text.search('tel:') + 4;
        try {
          tel = this.message_text.substring(startPos, startPos + 11);
          const afterReplaceText = ('<font color=#499DF2 >' + tel + '</font>');
          this.message_text = this.message_text.replace(tel, afterReplaceText);
        } catch (error) {
          tel = '';
        }
      }
      localStorage.setItem('onSendWebSocketMessageTag', 'true');
      const nowDate = Date.now();
      const msgKey = this.jid + '-' + this.toId + '-' + nowDate;
      const sendMsg = { tel, text: this.message_text, toId: this.toId, fromId: this.jid !== '' ? this.jid : localStorage.getItem('userId'), key: this.itemObj.id, type: 'general', nowDate };
      this.eventService.eventEmit.emit("onSendWebSocketMessage", sendMsg);
      this.messages.push({ msg: { type: 'general', message: this.message_text, tel, from: this.jid }, datetime: this.appGlobalService.getNowFormatDateYYYYMMDDHHMM(), key: msgKey });
      this.message_text = '';
      document.getElementById(this.sendBtnId).style.display = "none";
      document.getElementById(this.textareaId)['value'] = '';
      if (this.content) {
        this.content.scrollToBottom(0);
      }
      if (this.itemObj && this.itemObj['submit']) {
        const params = {
          content: this.itemObj['submit'].content,
          id: this.itemObj['submit'].id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.http.post("application/submit", params, res => {
          if (res.success) {
            console.log('submit after sendMessage');
          }
        });
      }
    } catch (error) {
      console.log("msg----->sendMessage error = " + JSON.stringify(error));
    }
  }

  openActivityModal() {
    let that = this;
    $('#' + that.chatModalId).fadeOut();
    const linkStr = localStorage.getItem('chatCustomBtnLink');
    const modalLink = JSON.parse(linkStr);
    if (modalLink) {
      that.pageModalService.openPage(modalLink, '', () => {
        that.showChooseList();
        that.content.scrollToBottom(0);
      });
    }

  }

  // 发送活动信息
  sendSelectItemMsg(data) {
    console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '', data);
    localStorage.setItem('onSendWebSocketMessageTag', 'true');
    const nowDate = Date.now();
    const msgKey = this.jid + '-' + this.toId + '-' + nowDate;
    this.eventService.eventEmit.emit("onSendWebSocketMessage",
      {
        text: data,
        toId: this.toId,
        fromId: this.jid,
        key: this.itemObj.id,
        type: 'opp',
        opportunity_id: data.id,
        title: data.title,
        rentunit: data.rentunit ? data.rentunit : '元/月',
        imags: data.imags,
        pluginId: data.pluginId,
        big_district: data.big_district,
        district: data.district,
        area: data.area,
        industry: data.industry,
        rent: data.rent,
        transfer_fee: data.transfer_fee,
        activity_reg_id: data.activity_reg_id,
        nowDate
      });
    this.messages.push({
      msg:
      {
        text: data,
        type: 'opp',
        opportunity_id: data.id,
        title: data.title,
        imags: data.imags,
        pluginId: data.pluginId,
        rentunit: data.rentunit ? data.rentunit : '元/月',
        from: this.jid,
        big_district: data.big_district,
        district: data.district,
        area: data.area,
        industry: data.industry,
        rent: data.rent,
        activity_reg_id: data.activity_reg_id,
        transfer_fee: data.transfer_fee ? data.transfer_fee : undefined
      }, datetime: this.appGlobalService.getNowFormatDateYYYYMMDDHHMM(),
      key: msgKey
    });
  }


  async sendShare() {
    $('#' + this.chatModalId).fadeOut();
    for (let i = 0, len = this.searchListData.length; i < len; i++) {
      ((i) => {
        setTimeout(() => {
          if (this.searchListData[i].isChecked) {
            localStorage.setItem('onSendWebSocketMessageTag', 'true');
            const data = this.searchListData[i];
            const nowDate = Date.now();
            const msgKey = this.jid + '-' + this.toId + '-' + nowDate;
            this.eventService.eventEmit.emit("onSendWebSocketMessage",
              {
                text: data,
                toId: this.toId,
                fromId: this.jid,
                key: this.itemObj.id,
                type: 'opp',
                opportunity_id: data.id,
                title: data.title,
                rentunit: data.rentunit ? data.rentunit : '元/月',
                imags: data.imags,
                pluginId: data.pluginId,
                big_district: data.big_district,
                district: data.district,
                area: data.area,
                industry: data.pluginId === "1" ? data.industry : data.build,
                rent: data.rent,
                transfer_fee: data.transfer_fee,
                nowDate
              });
            this.messages.push({
              msg:
              {
                text: data,
                type: 'opp',
                opportunity_id: data.id,
                title: data.title,
                imags: data.imags,
                pluginId: data.pluginId,
                rentunit: data.rentunit ? data.rentunit : '元/月',
                from: this.jid,
                big_district: data.big_district,
                district: data.district,
                area: data.area,
                industry: data.pluginId === "1" ? data.industry : data.build,
                rent: data.rent,
                transfer_fee: data.transfer_fee ? data.transfer_fee : undefined
              }, datetime: this.appGlobalService.getNowFormatDateYYYYMMDDHHMM(),
              key: msgKey
            });
          }
        }, (i + 1) * 50);
      })(i);
    }
    this.showMore();
    this.content.scrollToBottom(0);
  }

  async sendCaseShare() {
    this.shareShow = false;
    $('#' + this.chatModalId).fadeOut(300);
    for (let i = 0, len = this.caseListData.length; i < len; i++) {
      await setTimeout(() => {
        if (this.caseListData[i].isChecked) {
          localStorage.setItem('onSendWebSocketMessageTag', 'true');
          const data = this.caseListData[i];
          const nowDate = Date.now();
          const msgKey = this.jid + '-' + this.toId + '-' + nowDate;
          this.eventService.eventEmit.emit("onSendWebSocketMessage",
            {
              text: data,
              toId: this.toId,
              fromId: this.jid,
              key: this.itemObj.id,
              type: 'case',
              title: data.title,
              imags: data.pic,
              contractId: data.contract_id,
              caseType: data.pluginId,
              district: data.district,
              serviceDays: data.days,
              serviceOpinion: data.service_opinion,
              industry: data.industry,
              nowDate
            });
          this.messages.push({
            msg:
            {
              text: data,
              type: 'case',
              title: data.title,
              imags: data.pic,
              contractId: data.contract_id,
              caseType: data.pluginId,
              from: this.jid,
              serviceOpinion: data.service_opinion,
              serviceDays: data.days,
              district: data.district,
              industry: data.industry
            }, datetime: this.appGlobalService.getNowFormatDateYYYYMMDDHHMM(),
            key: msgKey
          });
        }
      }, 200);
    }
    this.showMore();
    this.content.scrollToBottom(0);
  }

  checkTime(i) {
    if (i < 10) { i = "0" + i; }
    return i;
  }

  getShare(pluginId) {
    const mobile =
      localStorage.getItem("loginAccount") &&
        localStorage.getItem("loginAccount") !== "undefined"
        ? localStorage.getItem("loginAccount")
        : "";
    this.caseListData = undefined;
    this.http.specialUrlPost('message/query/searchList', {
      cityId: 4403,
      ifNew: false,
      pageNo: 1,
      pageSize: 100,
      customerMobile: mobile,
      pluginId,
      client: "ppw",
    }, (res) => {
      const afterDecrypt = this.appGlobalService.decryptDes(res.data);

      this.searchListData = JSON.parse(afterDecrypt);
      if (this.searchListData.length > 0) {
        this.searchListData[0].isChecked = true;
      }
      $('#' + this.chatModalId).fadeIn(300);
      this.shareShow = !this.shareShow;
    }, (error) => {
      $('#' + this.chatModalId).fadeIn(300);
      this.shareShow = !this.shareShow;
    });
  }

  report() {
    try {
      // localStorage.setItem('reportPageId',this.tagData.data.agreement[2].label.link.target);
      const targetObj = { pageId: localStorage.getItem('reportPageId'), params: {}, sessionId: localStorage.getItem('sessionId') };
      this.appGlobalService.goToForward(targetObj);

    } catch (error) {
    }
  }

  invite() {
    try {
      // this.http.post()
      let tmpParams;
      if (this.appGlobalService.inviteBtn.link.params) {
        tmpParams = this.appGlobalService.inviteBtn.link.params;
      }
      const params = {
        params: { type: tmpParams.type, source_id: tmpParams.source_id },
        eventId: tmpParams.eventId,
        projectId: tmpParams.projectId,
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post("application/runEvent", params, res => {
        if (res && res.data) {
          let more = { listRemark: [] };
          console.log('submit after sendMessage', res);
          for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index];
            const tempData = { label: element.nickname, value: element.account };
            more.listRemark.push(tempData);
          }
          this.remarkList(more);
        }
      });

      // let more = { listRemark: [{ label: '石志军', value: '13662696947' }] };
      // this.remarkList(more);
      // localStorage.setItem('reportPageId',this.tagData.data.agreement[2].label.link.target);
      // const targetObj = { pageId: localStorage.getItem('reportPageId'), params: {}, sessionId: localStorage.getItem('sessionId') };
      // this.appGlobalService.goToForward(targetObj);
      // if (this.appGlobalService.inviteBtn) {
      //   this.pageModalService.openPage(this.appGlobalService.inviteBtn.link, (data) => {
      //     console.log('获取邀请的数据列表', data);
      //   });
      // }
      // 
    } catch (error) {
    }

  }

  remarkList(more) {
    const that = this;
    const buttons: any = [];
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          // this.webSocketService.sendCommandAppendGroup(more.listRemark[buttonIndex].value);
        }
      }
    );
  }






  getShareByArray(pluginIds, type?) {
    const mobile =
      localStorage.getItem("loginAccount") &&
        localStorage.getItem("loginAccount") !== "undefined"
        ? localStorage.getItem("loginAccount")
        : "";
    this.showType = type;
    this.caseListData = undefined;
    this.http.specialUrlPost('message/query/searchList', {
      cityId: 4403,
      ifNew: false,
      appType: 2,
      pageNo: 1,
      pageSize: 100,
      customerMobile: mobile,
      pluginIds
    }, (res) => {

      const afterDecrypt = this.appGlobalService.decryptDes(res.data);
      this.searchListData = JSON.parse(afterDecrypt);
      console.log(this.searchListData);
      if (this.searchListData.length > 0) {
        this.searchListData[0].isChecked = true;
      }
      $('#' + this.chatModalId).fadeIn(300);
      this.shareShow = !this.shareShow;
    }, (error) => {
      $('#' + this.chatModalId).fadeIn(300);
      this.shareShow = !this.shareShow;
    });
  }

  getCaseShare(pluginId) {
    this.searchListData = undefined;
    this.http.specialUrlPost('message/query/caseList', {
      cityId: 4403,
      ifNew: false,
      pageNo: 1,
      pageSize: 100,
      salesmanMobile: null,
      currentUserId: localStorage.getItem('connUserId'),
      pluginId
    }, (res) => {
      const afterDecrypt = this.appGlobalService.decryptDes(res.data);
      this.caseListData = JSON.parse(afterDecrypt);
      if (this.caseListData.length > 0) {
        this.caseListData[0].isChecked = true;
      }
      $('#' + this.chatModalId).fadeIn(300);
      this.shareShow = !this.shareShow;
    }, (error) => {
      $('#' + this.chatModalId).fadeIn(300);
      this.shareShow = !this.shareShow;
    });

  }

  shareitemdismiss() {
    this.shareShow = false;
    $('#' + this.chatModalId).fadeOut(300);
    console.log(this.shareShow, 'share');
  }
  showMore() {
    // this.more = !this.more;
    this.showChooseList();
  }

  showChooseList() {
    this.showMoreInfoBox = !this.showMoreInfoBox;
    if(this.showMoreInfoBox){
      $('#'+this.moreBtnId).addClass('showMoreInfoBox');
      $('#'+this.moreBtnId).removeClass('NotShowMoreInfoBox');
    }else{
      $('#'+this.moreBtnId).removeClass('showMoreInfoBox');
      $('#'+this.moreBtnId).addClass('NotShowMoreInfoBox');
    }
  }

  auto_grow() {
    let that = this;
    if (document.getElementById(that.textareaId)
      && document.getElementById(that.textareaId)['value']
      && document.getElementById(that.textareaId)['value'].length > 0
    ) {
      document.getElementById(that.sendBtnId).style.display = "block";
    } else {
      document.getElementById(that.sendBtnId).style.display = "none";
    }
  }


  // 跳转到商机详情
  goToPage(obj) {
    event.stopPropagation();
    if (this.isPxw === 'lj' || this.isPxw === 'js') {
      obj.type = "lj_opp";
    }
    if (obj.disableClick) {
      return; // 指定类型不可点击。
    }
    const params = {
      plugin_id: obj.pluginId, // 1:转让 2:出租 3: 选址
      type: obj.type,
      session: localStorage.getItem('sessionId')
    };
    this.http.post('element/pageId/getBySession', params, (res) => {
      if (res) {
        if (res.status === "fail") {
          return;
        }
        const pageParams = {
          pageId: res.page,
          params: { opportunity_id: obj.opportunity_id },
          sessionId: localStorage.getItem('sessionId')
        };
        this.appGlobalService.goToForward(pageParams);
      }
    });
  }




  goToCaseDetailPage(obj, pluginId, caseType, id) {
    event.stopPropagation();
    if (obj) {
      const pageParams = {
        pageId: obj.target,
        params: obj.params,
        sessionId: localStorage.getItem('sessionId')
      };
      this.appGlobalService.goToForward(pageParams);
    } else {
      const params = {
        plugin_id: pluginId, // 1:转让 2:出租 3: 选址
        type: caseType ? caseType : 'case',
        session: localStorage.getItem('sessionId')
      };
      this.http.post('element/pageId/getBySession', params, (res) => {
        if (res) {
          const pageParams = {
            pageId: res.page,
            params: { contract_id: id },
            sessionId: localStorage.getItem('sessionId')
          };
          this.appGlobalService.goToForward(pageParams);
        }
      });
    }
  }

  checkOppChange($event: any) {
    let count = 0;
    for (let i = 0, len = this.searchListData.length; i < len; i++) {
      if (this.searchListData[i].isChecked === true) {
        if (count === 3) {
          $event.target.checked = false;
          this.appGlobalService.showToast('最多只能发送三个' + (this.searchListData[i].pluginId === '3' ? '选址' : '物业' + '信息'), 2000, 'middle');
          break;
        } else {
          count++;
        }
      }
    }
  }

  checkCaseChange($event: any) {
    let count = 0;
    for (let i = 0, len = this.caseListData.length; i < len; i++) {
      if (this.caseListData[i].isChecked === true) {
        if (count === 3) {
          $event.target.checked = false;
          this.appGlobalService.showToast('最多只能发送三个案例信息', 2000, 'middle');
          return;
        } else {
          count++;
        }
      }
    }
  }

  showCall(phoneNumber) {
    event.stopPropagation();
    console.log('msg----->phoneNumber' + phoneNumber);
    this.http.changeCallNumber(phoneNumber);
  }

  hideSubDiv() {
    if (this.more) {
      this.more = false;
    }
  }


  loadData(event) {
    if(this.autoTriger){
      this.autoTriger = false;
      event.target.complete();
      return;
    }

    let newPageNo = this.chatService.pageNo +1;

    this.chatService.getChatHistoriesByFriendNo(this.itemObj.toId, (messageList) => {
      // 更新分页
      this.appGlobalService.consoleLog('消息读取成功！', messageList);
      this.http.hideLoading();
      event.target.complete();
    },newPageNo);

    // this.params.sessionId = this.sessionId;
    // 请求下一个页面
    // this.pageNo = this.pageNo + 1;
    // 请求获取新数据
    // this.http.post('application/submit', this.params, res => {
    //   // 请求数据成功
    //   // tslint:disable-next-line:no-string-literal
    //   if (res['success']) {
    //     // 追加返回数据
    //     // tslint:disable-next-line:no-string-literal
    //     if (Array.isArray(res['data']['data']) && res['data']['data'].length > 0) {
    //       // tslint:disable-next-line:no-string-literal
    //       setTimeout(() => {
    //         const newData = res['data']['data'].concat(this.tagData['data']['data']);
    //         this.tagData['data']['data'] = newData;
    //         event.target.complete();
    //       }, 1500);

    //       // 参数替换
    //       // tslint:disable-next-line:no-string-literal
    //       this.params = res['data'].submit;
    //     } else {
    //       this.disabled = true;
    //       event.target.complete();
    //       // 没有数据了
    //       // this.appGlobalService.showToast('没有数据了...', 1000, 'middle');
    //     }
    //   } else {
    //     // 请求失败，更新当前页数
    //     this.pageNo = this.pageNo - 1;
    //     // 请求数据失败
    //     // tslint:disable-next-line:no-string-literal
    //     this.appGlobalService.showToast(res['message'], 2000, 'middle');
    //     event.target.complete();
    //   }
    // });
  }



  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    this.appGlobalService.consoleLog('chatonline.component', 'remove refreshChatMsg');
    // 2024.08.05 fixed bug
    this.appGlobalService.addedMessages = new Set();
    this.chatService.actionFromChatOnlinePage = false;
    this.eventService.removeCustomListListenersByName('refreshChatMsg');
    this.eventService.eventEmit.emit('refreshChatInviteList', '1');
    this.appGlobalService.addedFormatTimes = new Set();
    localStorage.removeItem('recevieMsgLastTime');
  }
  ionViewWillLeave() {
    this.pageModalService.closeAllModal();// 2024.01.05 返回弹窗没有关闭
  }

}

